package com.icss.ah.expressBird.acton;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.expressBird.thread.ExpressBirdThread;
/**
 * 快递鸟回调响应
 * @author csadchen
 * @ date 2017-06-15
 */
@Controller
@Scope("prototype")
public class ExpressBirdAction extends BaseAction{
	//错误日志
	private final Logger errlog = Logger.getLogger("E");
	//info日志
	private final Logger infolog = Logger.getLogger("I");
	
	private HashMap reMap = new HashMap();
	/**
	 * 回调信息处理
	 */
	public void expressBird(){
		request = getRequest();
		response = getResponse();
		boolean result = false;
		//商户ID
		String EBusinessID = "";
		//失败原因
		String reason = "";
		//更新时间
		String updateTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
		try{
			reMap = new HashMap();
			if(request.getMethod().equalsIgnoreCase("get")){
				PrintWriter pw = response.getWriter();
				pw.println("success");
			} else if(request.getMethod().equalsIgnoreCase("post")){
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html");
				//获取快递鸟发送数据
				String RequestData = request.getParameter("RequestData");
				RequestData = RequestData == null ? "" : RequestData;
				//记录日志
				infolog.info("ExpressBirdAction|expressBird|RequestData:"+RequestData);
				//数据处理
				if(!RequestData.equals("")){
					//转json
					JSONObject json = JSONObject.fromObject(RequestData);
					//获取商户id
					EBusinessID = json.getString("EBusinessID");
					//获取快递单数量
					int count = json.getInt("Count");
					//获取快递单列表数据
					List dataList = json.getJSONArray("Data");
					if(!dataList.isEmpty()){
						//列表不为空进行处理并优先返回获取数据状态
						result = true;
						//调用线程处理快递单数据
						//初始化线程
						ExpressBirdThread ds1 = new ExpressBirdThread(EBusinessID,count,dataList,expressBirdService);
						//定义并启用线程
						Thread t1 = new Thread(ds1);
						t1.start();
					} else {
						//无列表数据直接返回
						result = false;
						reason = "Data内容为空";
					}
				} else {
					//未获取到发送数据，直接返回
					result = false;
					reason = "RequestData内容为空";
				}
				updateTime = DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss");
			}
		} catch (Exception e) {
			result = false;
			reason = e.getMessage();
			e.printStackTrace();
			//记录日志
			errlog.error("ExpressBirdAction|expressBird|异常：",e);
		} finally{
			try{
				PrintWriter pw = response.getWriter();
				reMap.put("Success", result);
				reMap.put("EBusinessID", EBusinessID);
				reMap.put("UpdateTime", updateTime);
				reMap.put("Reason", reason);
				JSONObject reJson = JSONObject.fromObject(reMap);
				pw.println(reJson.toString());
			} catch (Exception e) {
				e.printStackTrace();
				//记录日志
				errlog.error("ExpressBirdAction|expressBird|finally|异常：",e);
			}
		}
	}

}
